import {
    View, Text, TextInput, TouchableOpacity,
    ScrollView, Modal as ModalRN, Image,
} from 'react-native';
import React, { useState, useEffect } from 'react';
import {
    WingBlank, WhiteSpace, Button, Toast, Modal,
} from '@ant-design/react-native';
import FilePickerManager from 'react-native-file-picker';
import FileViewer from 'react-native-file-viewer';
import Feather from 'react-native-vector-icons/Feather';
import AntDesign from 'react-native-vector-icons/AntDesign';
import ImageViewer from 'react-native-image-zoom-viewer';
import { launchImageLibrary } from 'react-native-image-picker';
import DateTimePicker from '@react-native-community/datetimepicker';
import moment from 'moment';
import PropTypes from 'prop-types';
import styles from './styles';
import { saveMineLog, logDetail, editLog } from '../../../../comconfig/sqlfun';
import { debounce } from '../../../../utils/common';

const options = {
    mediaType: 'photo',
    cameraType: 'back',
    saveToPhotos: true,
    selectionLimit: 0,
};
const AddLog = ({ navigation, route }) => {
    const [workNameVal, setWorkNameValue] = useState('');
    const [workVal, setWorkValue] = useState('');
    const [unfinished, setUnfinished] = useState('');
    const [problem, setProblem] = useState('');
    const [fileUrls, setFileUrls] = useState([]);
    const [imgUri, setImgUri] = useState([]);
    const [images, setImages] = useState([]);
    const [viewPage, setViewPage] = useState(0);
    const [show, setShow] = useState(false);
    const [visible, setVisible] = useState(false);
    const [showdate, setShowDate] = useState(false);
    const [date, setDate] = useState(route.params.date === undefined
        ? new Date() : route.params.date);
    const [detail, setDetail] = useState({});
    const { isEditing, getLogList } = route.params;
    navigation.setOptions({
        headerRight: () => (
            <TouchableOpacity
                onPress={() => debounce(() => {
                    if (!route.params.isEditing) {
                        if (workNameVal === ''
                            || workVal === ''
                            || workNameVal.trim().length === 0
                            || workVal.trim().length === 0
                        ) {
                            Modal.alert(
                                <Text style={{ color: '#0F8DE9' }}>请输入完整</Text>,
                                null,
                                [
                                    { text: 'OK' },
                                ],
                            );
                            return;
                        }
                        saveMineLog(workNameVal, workVal,
                            unfinished, problem, imgUri, fileUrls, date.toString());
                        // eslint-disable-next-line no-unused-expressions
                        !route.params.home && getLogList();
                        navigation.goBack();
                    } else {
                        if (workNameVal === ''
                            || workVal === '0'
                            || workNameVal.trim().length === 0
                            || workVal.trim().length === 0
                        ) {
                            Modal.alert(
                                <Text style={{ color: '#0F8DE9' }}>请输入完整</Text>,
                                null,
                                [
                                    { text: 'OK' },
                                ],
                            );
                            return;
                        }
                        editLog(parseInt(route.params.id, 10), workNameVal, workVal,
                            unfinished, problem, imgUri, fileUrls, date.toString());
                        getLogList();
                        navigation.goBack();
                    }
                })}
            >
                <AntDesign
                    name="check"
                    size={26}
                    color="#017BFF"
                    style={{ marginRight: 5 }}
                />
            </TouchableOpacity>
        ),
    });
    const getDetail = async () => {
        try {
            const list = await logDetail(parseInt(route.params.id, 10));
            setDetail(JSON.parse(list));
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    useEffect(() => {
        if (isEditing) {
            getDetail();
        }
    }, []);
    useEffect(() => {
        if (JSON.stringify(detail) !== '{}') {
            setWorkNameValue(detail.workname);
            setWorkValue(detail.work);
            setUnfinished(detail.unfinished);
            setProblem(detail.problem);
            setFileUrls(JSON.parse(detail.fileurls));
            setImgUri(JSON.parse(detail.imgurls));
        }
    }, [detail]);

    const addImage = async () => {
        const addUri = [];
        const viewUri = [];
        const resFromLib = await launchImageLibrary(options);
        // const { uri } = resFromLib.assets[0];
        for (let i = 0; i < resFromLib.assets.length; i += 1) {
            const { uri } = resFromLib.assets[i];
            addUri.push(uri);
            viewUri.push({ url: uri });
        }
        setImgUri([...imgUri, ...addUri]);
        setImages([...images, ...viewUri]);
    };
    const delIamge = (i) => {
        Modal.operation(
            [
                {
                    text: '取消',
                    onPress: () => null,
                    style: { color: '#0F8DE9' },
                },
                {
                    text: '删除',
                    onPress: () => {
                        const copyImages = [...images];
                        copyImages.splice(i, 1);
                        const copyImgUri = [...imgUri];
                        copyImgUri.splice(i, 1);
                        setImgUri(copyImgUri);
                        setImages(copyImages);
                    },
                    style: { color: '#0F8DE9' },
                },
            ],
        );
    };
    const pickFile = () => {
        FilePickerManager.showFilePicker(null, (response) => {
            if (response.didCancel) {
                Toast.info('已取消', 1, undefined, false);
            } else if (response.error) {
                Toast.info(response.error, 1, undefined, false);
            } else {
                setFileUrls([...fileUrls, { fileName: response.fileName, path: response.path }]);
            }
        });
    };
    const delFile = (i) => {
        Modal.operation([
            {
                text: '删除',
                onPress: () => {
                    const copyFiles = [...fileUrls];
                    copyFiles.splice(i, 1);
                    setFileUrls(copyFiles);
                },
                style: { color: '#0F8DE9' },
            },
        ]);
    };
    const onChange = (event, selectedDate) => {
        const currentDate = selectedDate || date;
        setShowDate(false);
        setDate(currentDate);
    };
    return (
        <View>
            <ScrollView>
                <View style={styles.inputbg}>
                    <WingBlank>
                        <WhiteSpace />
                        <View
                            style={{ flexDirection: 'row' }}
                        >
                            <Text style={{ color: '#22C382', fontSize: 22 }}>
                                {`${moment(date).format('YYYY-MM-DD')}的日志`}
                            </Text>
                            <TouchableOpacity
                                onPress={() => setShowDate(true)}
                            >
                                <AntDesign
                                    name="calendar"
                                    size={30}
                                    color="#017BFF"
                                />
                            </TouchableOpacity>
                        </View>
                        <WhiteSpace />
                        <Text style={styles.title}>任务名字</Text>
                        <TextInput
                            placeholder="[任务名字][任务模块]"
                            placeholderTextColor="#5d5d7e"
                            style={styles.workname}
                            onChangeText={text => setWorkNameValue(text)}
                            value={workNameVal}
                            returnKeyLabel="done"
                        />
                        <WhiteSpace />
                        <Text style={styles.title}>任务内容</Text>
                        <TextInput
                            multiline
                            placeholder="内容描述..."
                            placeholderTextColor="#5d5d7e"
                            style={styles.textInput}
                            maxLength={200}
                            onChangeText={text => setWorkValue(text)}
                            value={workVal}
                            returnKeyLabel="done"
                        />
                        <WhiteSpace />
                        <Text style={styles.title}>未完成的工作</Text>
                        <TextInput
                            multiline
                            placeholder="..."
                            placeholderTextColor="#5d5d7e"
                            style={styles.textInput}
                            maxLength={200}
                            onChangeText={text => setUnfinished(text)}
                            value={unfinished}
                            returnKeyLabel="done"
                        />
                        <WhiteSpace />
                        <Text style={styles.title}>遇到的问题</Text>
                        <TextInput
                            multiline
                            placeholder="..."
                            placeholderTextColor="#5d5d7e"
                            style={styles.textInput}
                            maxLength={200}
                            onChangeText={text => setProblem(text)}
                            value={problem}
                            returnKeyLabel="done"
                        />
                        <WhiteSpace />
                    </WingBlank>
                </View>
                <View>
                    <WingBlank>
                        <WhiteSpace />
                        <TouchableOpacity
                            style={styles.pick}
                            onPress={() => { setShow(true); }}
                        >
                            <Text style={styles.title2}>图片</Text>
                        </TouchableOpacity>
                        <WhiteSpace />
                        {imgUri.length === 0 ? null : (
                            <View style={{
                                flexDirection: 'row',
                                flexWrap: 'wrap',
                                // justifyContent: 'space-around',
                            }}
                            >

                                {
                                    imgUri.map((uri, i) => (
                                        <TouchableOpacity
                                            key={Math.random(0, 1) * 100}
                                            onPress={() => { setVisible(true); setViewPage(i); }}
                                            onLongPress={() => delIamge(i)}
                                        >
                                            <Image
                                                style={styles.image}
                                                // resizeMethod
                                                resizeMode="contain"
                                                source={{
                                                    uri,
                                                }}
                                                defaultSource={
                                                    // eslint-disable-next-line max-len
                                                    require('../../../../assets/images/notfound.jpeg')
                                                }
                                            />
                                        </TouchableOpacity>
                                    ))
                                }
                            </View>
                        )}
                        <WhiteSpace />
                        <TouchableOpacity
                            style={styles.pick}
                            onPress={() => { pickFile(); }}
                        >
                            <Text style={styles.title2}>附件</Text>
                        </TouchableOpacity>
                        <WhiteSpace />
                        <View style={styles.filebg}>
                            {
                                fileUrls.map((objFile, i) => (
                                    <TouchableOpacity
                                        key={Math.random(0, 1)}
                                        onPress={() => {
                                            FileViewer.open(objFile.path)
                                                .then(() => {
                                                    // success
                                                })
                                                .catch((error) => {
                                                    // error
                                                    Toast.info(error, 1, undefined, false);
                                                });
                                        }}
                                        onLongPress={() => {
                                            delFile(i);
                                        }}
                                        style={styles.file}
                                    >
                                        <Feather
                                            name="file"
                                            size={40}
                                            color="#017BFF"
                                            style={{ marginRight: 5 }}
                                        />
                                        <Text
                                            numberOfLines={1}
                                            ellipsizeMode="middle"
                                        >
                                            {objFile.fileName}
                                        </Text>
                                    </TouchableOpacity>
                                ))
                            }
                        </View>
                    </WingBlank>
                </View>
                {showdate && (
                    <DateTimePicker
                        textColor="#108EE9"
                        testID="dateTimePicker"
                        value={new Date(date)}
                        mode="date"
                        is24Hour
                        display="default"
                        onChange={onChange}
                    />
                )}
                <Modal
                    popup
                    visible={show}
                    animationType="slide-up"
                    maskClosable
                    onClose={() => setShow(false)}
                >
                    <Button
                        style={{ borderWidth: 0 }}
                        onPress={() => { addImage(); setShow(false); }}
                    >
                        从相册选择
                    </Button>
                    <Button
                        style={{ borderWidth: 0 }}
                        onPress={() => setShow(false)}
                    >
                        取消
                    </Button>
                </Modal>
                <ModalRN visible={visible}>
                    <ImageViewer imageUrls={images} index={viewPage} />
                    <Button
                        style={{ borderWidth: 0 }}
                        onPress={() => setVisible(false)}
                    >
                        取消
                    </Button>
                </ModalRN>
            </ScrollView>
        </View>
    );
};
AddLog.defaultProps = {
    route: {},
};
AddLog.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),
};
export default AddLog;
